package com.stox.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.stox.converter.BeanMapper;
import com.stox.manager.CountryManager;
import com.stox.manager.ExchangeManager;
import com.stox.model.Exchange;
import com.stox.model.entity.ExchangeEntity;

@Controller
@RequestMapping(value="/exchanges")
public class ExchangeController implements InitializingBean{

	@Autowired
	private ExchangeManager exchangeManager;
	
	@Autowired
	private CountryManager countryManager;
	
	@Autowired
	private BeanMapper beanMapper;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		if(0 == exchangeManager.count()){
			exchangeManager.save(
					new ExchangeEntity("BSE","Bombay Stock Exchange",
							countryManager.findOne("IN")));
		}
	}
	
	@ResponseBody
	@SuppressWarnings("unchecked")
	@Cacheable("com.stox.model.entity.ExchangeEntity")
	@RequestMapping(value="/{countryCode}", method=RequestMethod.GET, produces="application/json")
	public List<ExchangeEntity> findByCountryCode(@PathVariable("countryCode") String countryCode){
		List<ExchangeEntity> exchangeEntities = exchangeManager.findByCountryCode(countryCode); 
		return beanMapper.map(exchangeEntities, ArrayList.class, Exchange.class);
	}
	
}
